package com.example.service;

import com.example.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RedisAuthService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    // 保存登录状态，延长至30分钟方便测试
    public void saveLoginStatus(String sessionId, String openId, String nickname, String avatar) {
        String key = "wechat:login:" + sessionId;
        String value = String.format("%s|%s|%s", openId, nickname, avatar);
        redisTemplate.opsForValue().set(key, value, 30, TimeUnit.MINUTES);
    }

    // 检查登录状态
    public boolean checkLoginStatus(String sessionId) {
        String key = "wechat:login:" + sessionId;
        return redisTemplate.hasKey(key);
    }

    // 获取登录用户openId
    public User getLoginUser(String sessionId) {
        String key = "wechat:login:" + sessionId;
        String value = redisTemplate.opsForValue().get(key);
        if (value == null) return null;

        String[] parts = value.split("\\|");
        User user = new User();
        user.setWechatOpenid(parts[0]);
        user.setNickname(parts[1]);
        user.setAvatar(parts[2]);
        return user;
    }
}